<template>
	<el-card class="box-card" shadow="hover" style="height: 100%" body-style="height:100%; overflow:auto">
		<template #header>
			<div class="card-header">
				<!-- <el-button type="primary" icon="ele-Plus" @click="openAddVillage('add')" > 新增小区 </el-button> -->
				<div class="tree-h-flex">
					<div class="tree-h-left">
						<el-input :prefix-icon="Search" v-model="filterText" placeholder="小区名称" />
					</div>
					<div class="tree-h-right">
						<el-dropdown @command="handleCommand">
							<el-button style="margin-left: 8px; width: 34px">
								<el-icon class="el-icon--center">
									<more-filled />
								</el-icon>
							</el-button>
							<template #dropdown>
								<el-dropdown-menu>
									<el-dropdown-item command="expandAll">全部展开</el-dropdown-item>
									<el-dropdown-item command="collapseAll">全部折叠</el-dropdown-item>
									<el-dropdown-item command="rootNode">根节点</el-dropdown-item>
									<el-dropdown-item command="refresh">刷新</el-dropdown-item>
								</el-dropdown-menu>
							</template>
						</el-dropdown>
					</div>
				</div>
			</div>
		</template>
		<!-- lazy :load="loadNode"
				:expand-on-click-node="false"-->
		<div style="margin-bottom: 45px" v-loading="state.loading">
			<el-tree ref="treeRef" class="filter-tree" :data="state.floorData" node-key="id"
				:props="{ children: 'children', label: 'name' }" :filter-node-method="filterNode"
				@node-click="nodeClick" highlight-current>
				<template #default="{ node, data }">
					<span class="custom-tree-node">
						<span>{{ node.label }}</span>
						<div @click.stop="()=>{}">
							<el-dropdown placement="right-start" trigger="click">
							<span class="el-dropdown-link" style="font-size: 18px">
								<el-icon>
									<Operation />
								</el-icon>
							</span>
							<template #dropdown>
								<el-dropdown-menu>
									<el-dropdown-item v-if="data.dataType===0" :icon="Plus"
										@click.native="openAddVillage('add')">新增小区</el-dropdown-item>
									<el-dropdown-item :icon="Plus"
										@click.native="openAddFloor(node,data)">新增子层级</el-dropdown-item>
									<el-dropdown-item v-if="data.dataType===1" :icon="Plus"
										@click.native="addFloorTree(node,data)">新增同层级</el-dropdown-item>
									<el-dropdown-item :icon="CirclePlusFilled"
										@click.native="addChildrenTree(node,data)">新增下级</el-dropdown-item>
									<el-dropdown-item v-if="data.dataType===0" :icon="Edit"
										@click.native="openUpdateVillage(node,data)">修改</el-dropdown-item>
									<el-dropdown-item v-if="data.dataType===1" :icon="Edit"
										@click.native="openUpdateFloor(node,data)">修改</el-dropdown-item>
									<el-dropdown-item v-if="data.isLeaf===1" :icon="Plus"
										@click.native="addHouse(node,data)">新增房产</el-dropdown-item>
									<el-dropdown-item :icon="Delete"
										@click.native="delTree(node,data)">删除</el-dropdown-item>
								</el-dropdown-menu>
							</template>
							</el-dropdown>
							<!-- <el-dropdown>
					<i class="el-icon-s-operation"></i>...
					<el-dropdown-menu slot="dropdown"> @mouseover="mouseover(data)" @mouseleave="mouseout(data)"
						<el-dropdown-item icon="el-icon-plus" @click.native="addPeerTree(node,data)">新增同级</el-dropdown-item>
						<el-dropdown-item icon="el-icon-circle-plus" @click.native="addChildrenTree(node,data)">新增下级</el-dropdown-item>
						<el-dropdown-item icon="el-icon-edit-outline" @click.native="updateTree(node,data)">修改</el-dropdown-item>
						<el-dropdown-item icon="el-icon-delete-solid" @click.native="delTree(node,data)">删除</el-dropdown-item>
					</el-dropdown-menu>
					</el-dropdown> -->
						</div>
					</span>
				</template>
			</el-tree>
			<!-- check-strictly  slot-scope="{ node, data }" v-show="state.dropdownShow"
				default-checked-keys="state.ownOrgData" 
				show-checkbox="state.isShowCheckbox"-->
		</div>
	</el-card>
	<EditVillage ref="editVillageRef" :title="state.editVillageTitle" @handleQuery="handleQuery" />
	<EditFloorFloor ref="editFloorRef" :title="state.editFloorTitle" @handleQuery="handleQuery" />
</template>

<script lang="ts" setup>
import { defineAsyncComponent, onMounted, reactive, ref, watch } from 'vue';
import type { ElTree } from 'element-plus';
import { Search,Operation,MoreFilled,Plus,CirclePlusFilled,Edit,Delete } from '@element-plus/icons-vue';
// import { Search, MoreFilled } from '@element-plus/icons-vue';
import { useResourceApi } from '/@/api/resource';
// import { useFloorApi } from '/@/api/resource/resource';
//import { getAPI } from '/@/utils/axios-utils';
//import { SysOrgApi } from '/@/api-services/api';
//import { SysOrg } from '/@/api-services/models';
//   import { useResourceApi } from '/@/api/resource';
  import { VillageForm } from '/@/api/village';

const filterText = ref('');
const treeRef = ref<InstanceType<typeof ElTree>>();
const state = reactive({
	loading: false,
	chdcount: 0,
	isShowdp :false,
	floorData: [] as Array<FloorItem>,
	isShowCheckbox: false,
	dropdownShow:false,
	editVillageTitle:'',
	editFloorTitle:'',
	// ownOrgData: [],
});
  const EditVillage = defineAsyncComponent(() => import('/@/views/main/house/component/editDialog.vue'));
  const EditFloorFloor = defineAsyncComponent(() => import('/@/views/main/house/component/editFloorDialog.vue'));

  const editVillageRef = ref<InstanceType<typeof EditVillage>>();
  const editFloorRef = ref<InstanceType<typeof EditFloorFloor>>();
onMounted(() => {
	initTreeData();
});

watch(filterText, (val) => {
	treeRef.value!.filter(val);
});
const openAddVillage = (type:string) => {
	state.editVillageTitle = '添加小区';
	const _row : VillageForm = { id: 0, villageName:'',villageCode:'',rentType:0,status:1 }
	console.log("_arow:"+JSON.stringify(_row))
	editVillageRef.value?.openDialog(type,_row);
};
const openUpdateVillage = (node, data) => {
	state.editVillageTitle = '修改小区';
	const _row: VillageForm = { id: data.id, villageName: data.name, villageCode: data.code, rentType: 0, status: 1 }
	console.log("_erow:"+JSON.stringify(_row))
	editVillageRef.value?.openDialog("edit",_row);
};
const openAddFloor  = (node, data)=> {
	//console.log('I see see');
	const _row : FloorItem = {"id":0,"pId":data.id,"vId":data.vId,"name":"","code":"","desc":"","isLeaf":false,"dataType":1,"rentType":data.rentType};
	if(data.dataType==0&&data.id==data.vId){
		_row.pId=0
	}
	editFloorRef.value?.openDialog('add', _row, 0);
	// console.log('node:'+JSON.stringify(node));
	// state.editFloorTitle = '添加小区';
	// const _row : VillageForm = { id: 0, villageName:'',villageCode:'',rentType:0,status:1 }
	// console.log("_row:"+JSON.stringify(_row))
	// editVillageRef.value?.openDialog(type,_row);
	//editConfigRef.value?.openDialog(type, { sysFlag: 2, orderNo: 100 });
};
const openUpdateFloor  = (node, data)=> {
	const _row : FloorForm = data;
	// if(data.dataType==0&&data.id==data.vId){
	// 	_row.pId=0
	// }
	editFloorRef.value?.openDialog('edit', _row, state.chdcount);
};

// 打开编辑页面
const openEditUser = (type: string, row: VillageForm) => {
	// state.editVillageTitle = '编辑账号';
	// editVillageRef.value?.openDialog(type, row);
};

const initTreeData = async () => {
	state.loading = true;
	useResourceApi().getFloorTreeList({"id":0,"dataType":-1,"rentType":0}).then((res: AjaxResult)=>{
		const _data : Array<FloorForm> = res.data??[];
		//console.log('ok-res:'+JSON.stringify(res.data));
		state.floorData = _data; //JSON.parse(JSON.stringify(res.data));
	});
	// var res = await getAPI(SysOrgApi).apiSysOrgListGet(0);
	// state.orgData = res.data.result ?? [];
	state.loading = false;
};
// 查询操作
const handleQuery = async () => {
		state.loading = true;
		initTreeData();
		// useUserApi().getUserPage(state.userTableData.queryParams).then(async (res: AjaxResult) => {
		// const _data: Array<UserForm> = res.data.items;
		// state.userTableData.data = _data;
		// state.userTableData.total = res.data?.total;
		// });
		setTimeout(() => {
			state.loading = false;
		}, 500);
	};
async function loadNode(node, resolve) {
	console.log('node:'+node.key);
	if(node.level===0){
		useResourceApi().getFloorTreeList({"id":0,"dataType":0,"rentType":0}).then((res: AjaxResult)=>{
			const _data : Array<FloorForm> = res.data;
			//console.log('ok-res:'+JSON.stringify(res.data));
			//state.floorData = _data??[]; //JSON.parse(JSON.stringify(res.data));
			resolve(_data);
		});
	}else{
		setTimeout(() => {
			useResourceApi().getFloorTreeList({"id":node.key,"dataType":1,"rentType":0}).then((res: AjaxResult)=>{
			const _data : Array<FloorForm> = res.data;
			resolve(_data);
		});
		}, 1000);
	}
}
// 设置默认选择
// const setCheckedKeys = (orgData: any) => {
// 	state.isShowCheckbox = true;
// 	treeRef.value!.setCheckedKeys([]);
// 	state.ownOrgData = orgData;
// };

// 获取已经选择
// const getCheckedKeys = () => {
// 	return treeRef.value!.getCheckedKeys();
// };

const filterNode = (value: string, data: Array<FloorItem>) => {
	if (!value) return true;
	return data.name.includes(value);
};

const handleCommand = async (command: string | number | object) => {
	if ('expandAll' == command) {
		for (let i = 0; i < treeRef.value!.store._getAllNodes().length; i++) {
			treeRef.value!.store._getAllNodes()[i].expanded = true;
		}
	} else if ('collapseAll' == command) {
		for (let i = 0; i < treeRef.value!.store._getAllNodes().length; i++) {
			treeRef.value!.store._getAllNodes()[i].expanded = false;
		}
	} else if ('refresh' == command) {
		initTreeData();
	} else if ('rootNode' == command) {
		emits('node-click', { id: 0, name: '' });
	}
};

	const mouseover = ()=> { // 移入
		state.isShowdp = true;
		// console.log('data:'+JSON.stringify(data));
		//state.dropdownShow=true;
       //this.$set(data, 'dropdownShow', true)
    };
    const mouseout = ()=> { // 移除
		state.isShowdp=false;
		// console.log('data:'+JSON.stringify(data));
		//state.dropdownShow=false;
      	//this.$set(data, 'dropdownShow', false)
    };
    const addFloorTree = (node, data)=> {
		console.log('data:'+JSON.stringify(data));
		console.log('node:'+node);
      console.log('新增同级')
    };
    const addChildrenTree = (node, data)=> {
      console.log('新增下级')
    };
    const updateTree = (node, data)=> {
      console.log('修改')
    };
    const updateTdelTreeree = (node, data)=> {
      console.log('删除')
    };

// 与父组件的交互逻辑
const emits = defineEmits(['node-click']);
const nodeClick = (node: any) => {
	const _chdcount = node.children?.length | 0;
	state.chdcount=_chdcount;
	console.log('nodeClick:'+JSON.stringify(node)+'		co:'+_chdcount);
	emits('node-click', { "id": node.id, "name": node.name,"pId":node.pId,"vId":node.vId,"vName":node.vName,"code":node.code,"desc":node.desc,"title":node.title,"isLeaf":node.isLeaf, "dataType":node.dataType,"rentType":node.rentType,"chdcount":_chdcount});
};

// 导出对象
defineExpose({ initTreeData });//, setCheckedKeys, getCheckedKeys });
</script>

<style lang="scss" scoped>
.tree-h-flex {
	display: flex;
}

.tree-h-left {
	flex: 1;
	width: 100%;
}

.tree-h-right {
	width: 42px;
	min-width: 42px;
}

// .custom-tree-node {
//   flex: 1;
//   display: flex;
//   align-items: center;
//   justify-content: space-between;
//   font-size: 14px;
//   padding-right: 8px;
// }

// .custom-tree-node {
//     flex: 1;
//     display: flex;
//     align-items: center;
//     justify-content: space-between;
//     font-size: 14px;
//     padding-right: 10px;
//     height:100%
//  }

.custom-tree-node {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: 14px;
	padding-right: 8px;
}

.show-hide:hover :nth-child(2) {
	display: inline-block !important;
}
</style>